<template>
	<view>
		<nav-bar :rightWidth="windowWidth-menuleft" leftWidth="20">
			<template #left>
				<uni-icons type="arrowleft" size="22" color="#999" @click="back"></uni-icons>
			</template>
			<template #mid>
				<view class="na-input-view" :style="{'height':menuHeight+'px','bottom':paddingBottom+'px'}">
					<input confirm-type="search" class="nav-bar-input" type="text" placeholder="输入搜索关键词"
						@confirm="confirm" @input="input" :value="inputClearValue" />
					<uni-icons v-if="showClearIcon" class="clear-icon" type="clear" size="20" :style="{'right':60+'px'}"
						@click="clearIcon"></uni-icons>
					<button type="primary" class="search-btn" :style="{'height':menuHeight*0.9+'px'}" @click="saveSearchHistory">搜索</button>
				</view>
			</template>
		</nav-bar>

		<!-- 搜索建议列表 v-if="searchList.length!==0" -->
		<view class="sugg_list" :style="{'visibility':sugg_visible}">
			<view class="sugg_item" v-for="(item,i) in searchList" :key="i" @click="gotoDetail(item.goods_id)">
				<view class="goods_name">{{item.goods_name}}</view>
				<uni-icons type="arrowright"></uni-icons>
			</view>
		</view>
		<view :style="{'visibility':historyBoxVisibility}">
			<!-- 搜索历史 -->
			<view class="history-box"  v-if="historyList.length!==0">
				<!-- 标题 -->
				<view class="history-title">
					<text>搜索历史</text>
					<uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
				</view>
				<!-- 历史列表 -->
				<view class="history-list" id="historylist" :style="{'visibility':visible}" >
					<view v-for="(item,i) in viewDepartmentsTags" :key="i" @longtap="onLongPress(i)" id="historybox">
						<uni-tag inverted="true" custom-style="margin-top:5px;margin-right:5px;" :text="item"
							@click="gotoGoodsList(item)"></uni-tag>
					</view>
					<view> 
						<uni-icons type="arrowdown" color="#999" v-show="isShowTag==1" id="btn-down" @click="isShowDepartmentTag('open')"></uni-icons>
					</view>
					<view>
						<uni-icons type="arrowup" color="#999" v-show="isShowTag==2"  @click="isShowDepartmentTag('put')"></uni-icons>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		mapState,
		mapGetters
	} from 'vuex'
	export default {
		computed: {
			...mapState('pb_Prototype', ['statusBarH', 'customBarH', 'paddingTop', 'paddingButtom', 'menuHeight','windowWidth', 'menuleft']),
			...mapGetters('pb_Prototype', ['navBarHeight', 'menuBotton']),
			histories() {
				return [...this.historyList].reverse()
				//return this.viewDepartmentsTags
			}
			
		},
	
		data() {
			return {
				
				timer: null,
				kw: '',
				searchList: [],
				historyList: [],
				//wwidth:getApp().globalData.statusBarH,
				wheight: this.customBarH,
				showClearIcon: false,
				inputClearValue: '',
				towLineCount:0,
				departmentsTags:[],
				isShowTag:0,
				onelineTag:[],
				viewDepartmentsTags:[],
				visible:'hidden',
				sugg_visible:'hidden',
				sugg_index:'-999',
				historyBoxVisibility:'visible'

			};
		},
		mounted() {
			
			this.getDepartmentsTagData();
			// const query = uni.createSelectorQuery().in(this);
			// query.select('#historylist').boundingClientRect(data => {
			//   console.log("得到布局位置信息" + JSON.stringify(data));
			//   console.log("节点离页面顶部的距离为" + data.top);
			// }).exec();
		},

		methods: {
			getDepartmentsTagData(){
				//this.departmentsTags = this.departments;
				this.viewDepartmentsTags = this.departmentsTags; // -
				//console.log(this.departmentsTags)
				this.$nextTick(() => {
				    setTimeout(() => {
				        this.getInfo();
				    }, 0);
				});           
				//this.saveSearchHistory()
			},
			back() {
			
				uni.navigateBack()
			},
			input(e) {
				
				clearTimeout(this.timer)

				this.timer = setTimeout(() => {
					this.kw = e.detail.value
					this.inputClearValue = e.detail.value;
					if (e.detail.value.length > 0) {
						this.showClearIcon = true;
						this.sugg_visible='true'
					} else {
						this.showClearIcon = false;
						this.sugg_visible='false'
					}
					this.getSearchList()
					
				}, 500)
				

			},
			async getSearchList() {
				this.historyBoxVisibility='visible'
				this.visible='visible'
				if (this.kw.trim() === '') {
					this.searchList = []
					return
				}
				const {data: res} = await uni.$http.get('/api/public/v1/goods/qsearch', {
					query: this.kw
				})
				if (res.meta.status !== 200) return uni.$showMsg()
				this.searchList = res.message
				if(this.searchList.length!==0){
					this.historyBoxVisibility='hidden'
					this.visible='hidden'
				}
				
				//保存搜索建议
				//this.saveSearchHistory()
			},
			gotoDetail(goods_id) {
				this.saveSearchHistory()
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?id=' + goods_id
				})
				//
			},
			saveSearchHistory() {
				const set = new Set(this.historyList)
				set.delete(this.kw)
				set.add(this.kw)
				this.historyList = Array.from(set)
				// this.historyList.push(this.kw)
				uni.setStorageSync('kw', JSON.stringify(this.historyList))
				this.departmentsTags=[...this.historyList].reverse()
				this.getDepartmentsTagData()
			},
			clearHistory() {
				this.historyList = [],
				this.departmentsTags=[...this.historyList].reverse(),
					uni.setStorageSync('kw', '[]')
					
			},
			gotoGoodsList(kw) {
				this.saveSearchHistory()
				uni.navigateTo({
					url: '/subpkg/goods_list/goods_list?query=' + kw
				})
			},

			clearIcon() {
				this.inputClearValue = '';
				this.showClearIcon = false;
				this.searchList = [];
				this.historyBoxVisibility='visible'
				this.visible='visible'
				//this.getSearchList();
			},

			// 长按删除
			onLongPress(e) {
				let index0 = this.historyList.length - 1 - e
				var that = this
				uni.showModal({ // 弹框询问是否进行下一步事件
					title: '提示',
					content: '是否删除该搜索历史',

					success: function(res) {
						if (res.confirm) {
							//console.log(historyList)
							that.historyList.splice(index0, 1)
							//console.log(historyList)
							uni.setStorageSync('kw', JSON.stringify(that.historyList))

						} else if (res.cancel) {
							console.log('用户点击取消');
							return
						}
					}
				});
			},
			getInfomation(){
				//const oneTabLeft=0;//获取第一行第一个tab标签左边距
				//const contentDomWidth=0;//获取容器宽度
				//const fontwidth=0;//文字长度
				//const oneTabRight=0;//获取第一行第一个tab标签右边距
				//（内边距+文字长度）tab宽度和  小于  容器宽度
				const query=uni.createSelectorQuery().in(this)
				const historItem=uni.createSelectorQuery().selectAll('#historybox')
				const historList=uni.createSelectorQuery().select('#historylist')
				const downBtn=uni.createSelectorQuery().select('#btn-down')
				//const query = uni.createSelectorQuery().in(this);
				query.select('#historylist').boundingClientRect(data => {
				  console.log("得到布局位置信息" + JSON.stringify(data));
				  console.log("节点离页面顶部的距离为" + data.top);
				}).exec();
				
			},
			getInfo(){
				console.log('data')
				let departmentsTagsArrIndex=-1;
				let departmentsTagsArr = [];
				const query=uni.createSelectorQuery().in(this)
				const historItem=uni.createSelectorQuery().selectAll('#historybox')
				const historList=uni.createSelectorQuery().selectAll('#historylist')
				const downBtn=uni.createSelectorQuery().selectAll('#btn-down')
				
				
				historItem.fields({ rect: true, dataset: true }).exec(data => {
					if(this.departmentsTags.length===0) return
					
					const oneTabLeft=data[0][0].left;
					//console.log(data)
					
					data[0].forEach(item=>{
						if(item.left===oneTabLeft){
							departmentsTagsArrIndex++;
							departmentsTagsArr[departmentsTagsArrIndex]=[];
						}
						departmentsTagsArr[departmentsTagsArrIndex].push(item)
					})
					
				});
				uni.createSelectorQuery().selectAll('#historylist').fields({ size : true }).exec(contentDom => {
					 //console.log(contentDom[0][0])
					 if(this.departmentsTags.length===0) return
					 const contentDomWidth = contentDom[0][0].width;
			
					 //行数大于1
					 if (departmentsTagsArr.length > 2) {
					     //显示展开按钮
					     this.isShowTag = 1;
					     this.$nextTick(() => {
					         //获取展开按钮节点的宽度
					         downBtn.fields({ size:true }).exec(moreDomData => {
								//过滤出没有超出第一行的所有tag标签
								// const fliterTwoLineTags= departmentsTagsArr.slice(0,2)
					             let fliterNoExceedingTwolineTags = departmentsTagsArr[1].filter(item => {
					                 return item.right + moreDomData[0][0].width <= contentDomWidth;
					             });
								  
								 fliterNoExceedingTwolineTags=departmentsTagsArr[0].concat(fliterNoExceedingTwolineTags)
								
					             //切割并保存--标签收起时要用 
					             this.onelineTag = this.departmentsTags.slice(0, fliterNoExceedingTwolineTags.length);
								 this.viewDepartmentsTags = this.onelineTag;
								
					         });
					     });
					 } else {
					     //不显示展开/收起按钮
					     this.isShowTag = 0;
					 }                 
				});	
				this.visible='visible'
			},
			//展开全部标签
			isShowDepartmentTag(type) {
			    if (type == "open") {
			        this.isShowTag = 2;
			        this.viewDepartmentsTags = this.departmentsTags;
			    } else {
			        this.isShowTag = 1;
			        this.viewDepartmentsTags = this.onelineTag;
			    }
			},       

		},
		
		onLoad() {
			this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
			this.departmentsTags=[...this.historyList].reverse()

		}
		,onShow() {
			this.inputClearValue=''
			//this.sugg_visible='hidden',
		
		}

	}
</script>

<style lang="scss">
	.navbar_box {
		display: flex;
		//align-items: center;
		//padding-bottom:20px;
		background-color: white;
		border: 2px solid #C00000;
		
	}


	.search-box {
		background-color: #FFFFFF;
		//background-color: gray;
		position: sticky;
		top: 0;
		z-index: 999;
		//visibility: visible;

		uni-search-bar: {
			border: 2px solid #c00000;
		}

	}

	.sugg_list {
		padding: 0 5px;

		.sugg_item {
			font-size: 12px;
			padding: 13px 0;
			border-bottom: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.goods_name {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				margin-right: 3px;

			}
		}

	}

	.history-box {
		padding: 0 5px;

		.history-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 40px;
			font-size: 13px;
			border: 1px solid #efefef;
		}

		.history-list {
			display: flex;
			flex-wrap: wrap;
			visibility: hidden;
			// overflow: hidden;
			// -webkit-line-clamp: 2;
			// text-overflow: ellipsis;
			// display: -webkit-box;
			// -webkit-box-orient: vertical;


			.uni-tag {
				display: inline-block;
			}
		}

	}

	.na-input-view {
		display: flex;
		//flex-direction: row;
		align-items: center;
		background-color: #CCCCCC;
		border-radius: 15px;
		flex-wrap: nowrap;
		position: sticky;
		//height: 32px;
		box-shadow: 2px #FFFFFF;
		padding-right: 2px;
		padding-left: 10px;
		justify-content: space-between;

		.nav-bar-input {
			font-size: 13px;
			padding-right: 0px;
		}

		.clear-icon {
			position: absolute;
			//color: #CCCCCC;

			z-index: 999;


		}

		.search-btn {
			background-color: #F00000;
			width: 50px;
			padding-right: 1px;
			border-radius: 15px;
			font-size: 12px;
			display: flex;
			align-items: center;
			//align-content: center;
			//justify-content: center;
			justify-items: center;

		}

	}
</style>